<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="nickname" label="治疗师">
                  <a-input
                    v-model="formModel.nickname"
                    placeholder="请输入治疗师"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="groupNamezh" label="组织">
                  <a-cascader
                    v-model="formModel.deptId"
                    check-strictly
                    :options="organizations"
                    placeholder="请选择所在组织"
                    :field-names="organizationsFields"
                    :show-all-levels="false"
                    @change="changsd"
                    allow-clear
                  ></a-cascader>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="startDates" label="日期">
                  <a-range-picker
                    v-model="formModel.startDates"
                    style="width: 360px; margin: 0 24px 24px 0"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
              <!--  -->
              <a-col :span="5">
                <a-space :size="18">
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <a-table
        ref="userList"
        row-key="userId"
        v-model:selectedKeys="userIds"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :row-selection="rowSelection"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- groupName -->
        <template #groupName="{ record }">
          {{ record.groupName }}/{{ record.attribute }}
        </template>

        <template #startTime="{ record }">
          {{ record.startTime }}-{{ record.endTime }}
        </template>

        <template #option="{ record }">
          <a-space :size="18">
            <div @click="openEdit(record)" class="zdivbot">个人信息</div>
            <div @click="openEdits(record)" class="zdivbot">预约详情</div>
            <div
              @click="openDelete(record)"
              v-if="record.username != 'admin'"
              class="zdivbotdel"
            >
              删除</div
            >
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/loading';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import { restList } from '@/api/restList.ts';
  import { organizationTree } from '@/api/organization.ts';
  const { loading, setLoading } = useLoading(true);
  const generateFormModel = () => {
    return {
      startDates: [],
      startDate: '',
      endDate: '',
      nickname: '',
    };
  };

  const formModel = ref(generateFormModel());

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const renderData = ref([]);
  const userList = ref();
  const fetchData = async () => {
    setLoading(true);
    try {
      console.log('当前数据', formModel.value);
      formModel.value.endDate = formModel.value.startDates[1];
      formModel.value.startDate = formModel.value.startDates[0];
      formModel.value.startDates = '';
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      restList(data).then((res) => {
        let list = res.data.list || [];
        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };

  const userIds = ref([]);

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    // {
    //   title: '插槽',
    //   dataIndex: 'patientTreatmentId',
    //   slotName: 'patientTreatmentId',
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '锁定时间',
      dataIndex: 'startTime',
      slotName: 'startTime',
    },

    {
      title: '治疗师',
      dataIndex: 'createUser',
    },
    {
      title: '所属',
      dataIndex: 'groupName',
      slotName: 'groupName',
    },
    {
      title: '锁定时长',
      dataIndex: 'duration',
    },
  ]);

  const changsd = (value) => {
    formModel.value.groupName = '';
    formModel.value.attribute = '';
    function findParentIdById(idToFind) {
      for (let i = 0; i < organizations.value.length; i++) {
        const item = organizations.value[i];
        if (item.id === idToFind) {
          return item.parentId;
        }
        if (item.children) {
          for (let j = 0; j < item.children.length; j++) {
            const childItem = item.children[j];
            if (childItem.id === idToFind) {
              return item.id;
            }
            if (childItem.children) {
              for (let k = 0; k < childItem.children.length; k++) {
                const grandChildItem = childItem.children[k];
                if (grandChildItem.id === idToFind) {
                  return childItem.id;
                }
              }
            }
          }
        }
      }
      return null;
    }
    const parentId = findParentIdById(value);

    formModel.value.attribute = value;
    formModel.value.groupName = parentId;
    if (parentId == 0) {
      formModel.value.attribute = '';
      formModel.value.groupName = value;
    }
  };
  const organizations = ref([]);

  const getOrganizations = () => {
    organizationTree().then((res) => {
      organizations.value = res.data || [];
    });
  };
  getOrganizations();
  const organizationsFields = {
    value: 'id',
    label: 'name',
  };
</script>

<style lang="scss" scoped></style>
